<?php
class Notice_Email_Event 
{
	private $_mid;
	private $_partly_start_time;

	/**
	 * 初始化邮件事件管理器
	 *
	 * @param	string	title
	 * @param	string	day of the time ie: "2012-06-07"
	 */
	public function __construct ($title, $day, $partly_start_time = NULL)
	{
		$date = $day; 
		$this->_mid = md5($title . '_' . $date);
		$this->_partly_start = $partly_start_time;
	}

	/**
	 * 发送事件：邮件任务已生成
	 *
	 * @param	array	$task = array(
	 *		'title' => String, 邮件标题
	 *		'start_time' => String, 邮件开始时间 2012-06-07
	 *		'groups'=> array, 邮件接收人的群组
	 *		'status'=> String, 邮件任务的状态：<'wait', 'started', 'finished', 'canceled'>
	 *		'comment'=> String, 邮件任务的注释
	 *	)
	 * @return	void
	 */
	public function create ($email)
	{
		//
		// 这里应该添加针对title, time和construct参数的一致性比对
		//
		events::notify(Kohana::config('events.system.mass-mail'), array(
				'mailid'  => $this->_mid,
				'title'   => Arr::get($email, 'title'),
				'time'    => strtotime((int) Arr::get($email, 'start_time')),
				'groups'  => Arr::get($email, 'groups', array()),
				'status'  => Arr::get($email, 'status', 'wait'),
				'comment' => Arr::get($email, 'comment', ''),
			));
	}

	public function start ()
	{
		events::notify(Kohana::config('events.system.mass-mail'), array(
				'mailid'  => $this->_mid,
				'status'  => 'started',
			));
	}

	public function finish ()
	{
		events::notify(Kohana::config('events.system.mass-mail'), array(
				'mailid'  => $this->_mid,
				'status'  => 'finished',
			));
	}

	public function cancel ()
	{
		events::notify(Kohana::config('events.system.mass-mail'), array(
				'mailid'  => $this->_mid,
				'status'  => 'canceled',
			));
	}

	public function partly_start ($start_time, $send = 0)
	{
		$send       = (int) $send;
		$start_time = (int) $start_time;
		$this->_partly_start = $start_time;

		events::notify(Kohana::config('events.system.mass-mail'), array(
				'mailid' => $this->_mid,
				'start'  => $start_time,
				'send'   => $send,
			));
	}

	public function partly_stop ($end_time = NULL)
	{
		$end_time = NULL === $end_time ? time() : (int) $end_time;

		if ($this->_partly_start <= 0)
			return ;

		events::notify(Kohana::config('events.system.mass-mail'), array(
				'mailid' => $this->_mid,
				'start'  => $this->_partly_start,
				'end'    => $end_time,
			));
	}

	public function partly_report ($send)
	{
		$end_time = NULL === $end_time ? time() : (int) $end_time;

		if ($this->_partly_start <= 0)
			return ;

		events::notify(Kohana::config('events.system.mass-mail'), array(
				'mailid' => $this->_mid,
				'start'  => $this->_partly_start,
				'send'   => (int) $send,
			));
	}
}
